import 'package:fig/events/spider_event.dart';
import 'package:fig/models/master_media_spider.dart';
import 'package:fig/utils/config.dart';
import 'package:flutter/material.dart';

class HomeSettingPageWidget extends StatefulWidget {
  const HomeSettingPageWidget();

  @override
  State<StatefulWidget> createState() => _HomeSettingPageWidget();
}

class _HomeSettingPageWidget extends State<HomeSettingPageWidget> {
  var _spiderSwitchValue = false;
  var _spiderGroupSelected = 1;
  var _spiderCacheValue = false;

  void onSpiderSelectedChanged(int selected) {
    setState(() {
      _spiderGroupSelected = selected;
    });

    // 更新数据库中的配置
    Config.setSpider(Config.spiderPool[selected - 1].id);
    Config.eventBus.fire(SpiderChangedEvent()); // 通知消费者，修改了（爬虫）数据来源
  }

  void onSpiderSwitchChanged(bool status) {
    setState(() {
      _spiderSwitchValue = status;
    });

    // 更新数据库中的配置
    Config.setAutoSpider(status);
    Config.eventBus.fire(SpiderWorkingEvent(status)); // 开关爬虫
  }

  @override
  void initState() {
    super.initState();

    // 初始化爬虫开关
    setState(() {
      _spiderSwitchValue = Config.autoSpider();
    });

    // 初始化“数据来源”
    for (var i = 0; i < Config.spiderPool.length; i++) {
      if (Config.selectedSpider() == Config.spiderPool[i].id) {
        setState(() {
          _spiderGroupSelected = i + 1;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    const padding = EdgeInsets.only(left: 16, top: 16);
    return Scaffold(
      appBar: AppBar(
        title: Text("全局设置"),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SwitchListTile(title: Text('采集开关'), value: _spiderSwitchValue, onChanged: onSpiderSwitchChanged),
          Padding(padding: padding, child: Text('选择数据来源')),
          for (MasterMediaSpider _spiderConfig in Config.spiderPool)
            RadioListTile<int>(
              title: Text('${_spiderConfig.name} (${_spiderConfig.apiUrl})'),
              value: _spiderConfig.id,
              groupValue: _spiderGroupSelected,
              onChanged: onSpiderSelectedChanged,
            ),
          Padding(padding: padding, child: Text('----------待开放功能----------')),
          SwitchListTile(title: Text('缓存图片信息'), value: _spiderCacheValue),
          Padding(padding: EdgeInsets.only(left: 16), child: RaisedButton(child: Text('重置该来源数据（删除已爬起信息，并重新爬取）'), onPressed: null)),
        ],
      ),
    );
  }
}
